import 'dart:convert';

import 'package:flutter_demo/entities/article_item.dart';
import 'package:get/get.dart';
import 'package:html/parser.dart' as htmlparser;
import 'package:html/dom.dart' as dom;

class DomParser {
  static List<ArticleItem> parseArtilceList(String? data) {
    dom.Document document = htmlparser.parse(data);
    var contents = document.getElementsByClassName("row posts-wrapper");
    final list = List<ArticleItem>.empty(growable: true);
    if (contents.isEmpty) {
      return list;
    }
    var content = contents[0];
    for (var element in content.children) {
      var articleItem = ArticleItem();
      var media = element.getElementsByClassName("entry-media")[0];
      articleItem.cover = media.getElementsByTagName("img")[0].attributes["data-src"];

      var wrapper = element.getElementsByClassName("entry-wrapper")[0];
      var category = wrapper.getElementsByClassName("meta-category")[0];
      articleItem.tags = category.getElementsByTagName("a").map((e) => e.text.trim()).toList();

      var title = wrapper.getElementsByClassName("entry-title")[0];
      var link = title.getElementsByTagName("a")[0];
      articleItem.title = title.text.trim();
      articleItem.link = link.attributes["href"].toString();
      list.add(articleItem);
    }
    return list;
  }

  static parseArticleTags() {

  }

  static parseDownloadLink() {

  }

  static String? parseVideo(dom.Element element) {
    final scriptText = element.text;
    try {
      final start = scriptText.indexOf("video: {");
      final end = scriptText.lastIndexOf("type: ");
      final videoStr = scriptText.substring(start, end);
      return videoStr.substring(videoStr.indexOf("\"") + 1, videoStr.lastIndexOf("\""));
    } catch(e) {
      Get.log("aaa,,${e}");
      return null;
    }
  }
}